<?php

namespace app\common\logic;



use EasyWeChat\Factory;
use think\exception\ValidateException;

/**
 * Token接口
 */
class Qrcode
{

    private $config = [];
    /**
     * 对象
     */
    private $app = null;
    private $page = 'pages/login/authorize';
    public function __construct()
    {
        $wx = config('site.wxapp');
        $config = [
            'app_id' => $wx['wxappid'],
            'secret' => $wx['wxappsecret'],

            'response_type' => 'array',

            'log' => [
                'level' => 'debug',
                'file' => 'wechat.log',
            ],
        ];

        $this->config = array_merge($config);
        $this->page = config('site.wx_share_path');

        $this->app = Factory::miniProgram($config);

    }

    /**
     * 生成二维码
     */
    public  function createQr($scene, $fileName) {
        $dir = ROOT_PATH.'public'.DS.'uploads'.DS.'qrcode';
        if(!is_dir($dir)){
            mkdir($dir);
        }

        $realPath = $dir . DS . $fileName;
        $savePath = str_replace(ROOT_PATH.'public', '', $realPath);
        if( is_file($realPath) ) {
            return $savePath;
        }
        $response = $this->app->app_code->getUnlimit($scene, [
            'page'  => $this->page,
            'width' => 600,
        ]);
        if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
            $filename = $response->save($dir, $fileName);
        } else {
            throw new ValidateException('生成小程序码失败');
        }

        return $savePath;
    }
}
